<template>
  <transition>
    <div class="salesman-add-user">
      <div class="module-form app-main">
        <mt-cell
          title="门店类型" class="mint-field">
          <select v-model="post.storeType" class="select-operator">
            <option value="2">汽车修理厂</option>
            <option value="1">汽车玻璃门店</option>
          </select>
        </mt-cell>
        <mt-field label="门店名称" placeholder="请输入门店名称" v-model="post.storeName"></mt-field>
        <mt-field label="门店地址" placeholder="请输入门店地址" v-model="post.address"></mt-field>
        <mt-field label="登陆账号/手机号码" placeholder="请输入登陆账号/手机号" v-model="post.linkPhone"></mt-field>
        <mt-field label="用户名" placeholder="请输入用户名" v-model="post.linkName"></mt-field>

        <mt-cell
          title="门头照" class="mint-field mint-field-img">
          <dl class="img-upload-content me-row">
            <dd class="item me-col-3" v-for="(item,index) in files" v-if="item.fileLocate=='实体门店图'">
              <span class="iconfont icon-shanchu" @click="handleDelImg(index,item)"></span>
              <img class="img" :src="item.src" @click="handleCheckPic(index)"/>
            </dd>
            <dd class="item me-col-3 item-add " @click="handleSelectImg('实体门店图')">
              <span class="iconfont add-img icon-jiahao"></span>
            </dd>
          </dl>
        </mt-cell>
        <mt-cell
          title="其他" class="mint-field mint-field-img">
          <dl class="img-upload-content me-row">
            <dd class="item me-col-3" v-for="(item,index) in files" v-if="item.fileLocate=='其他'">
              <span class="iconfont icon-shanchu" @click="handleDelImg(index,item)"></span>
              <img class="img" :src="item.src" @click="handleCheckPic(index)"/>
            </dd>
            <dd class="item me-col-3 item-add" @click="handleSelectImg('其他')">
              <span class="iconfont add-img icon-jiahao"></span>
            </dd>
          </dl>
        </mt-cell>
        <div class="button-content">
          <mt-button type="primary" @click="handleAdd">确认提交</mt-button>
        </div>
      </div>
      <mt-popup
        v-model="popupCorrect"
        position="bottom"
        class="correct-popup">
        <div class="tips-content">
          <span class="iconfont icon-chenggong"></span>
          <span class="tips">提交成功</span>
        </div>
      </mt-popup>
    </div>
  </transition>
</template>

<script>
  import { Header,Cell,Field,Button,Toast,Indicator} from 'mint-ui';
  export default {
    components:{
      Header,
      Cell,
    },
    data () {
      return {

        files:[],
        popupCorrect:false,

        mediaAttr:[],
        myUploads:'',
        accessToken:'',
        post:{
          linkPhone:'',
          linkName:'',
          storeType:'2',
          storeName:'',
          address:'',
          otherImgOss:'',
          shopImgOss:'',
        },
      }
    },
    beforeRouteEnter (to, from, next) {
      var u = navigator.userAgent;
      var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
      // XXX: 修复iOS版微信HTML5 History兼容性问题
      if (isiOS && to.path !== location.pathname) {
        // 此处不可使用location.replace
        location.assign(to.fullPath)
      } else {
        next()
      }
    },
    created(){
      var turl=(location.href).split('/')[2];
      var getCode=(location.href).split('code=')[1];
      var wxcode='';
      if(typeof getCode!=='undefined'){
        wxcode=getCode.split('&')[0];
      }else{
        wxcode=''
      }
      var params = new URLSearchParams();
      params.append('thisUrl',location.href);
      params.append('wxCode',wxcode);
      this.$axios({
        method: 'post',
        url:'gp/Oauth/authorizeUser',
        data:params,
      }).then((res)=>{
        if(res.data.statusCode==300){
        window.location.href=res.data.object;
      }else if(res.data.statusCode==200){
        this.post.openId=res.data.object.split('-----')[0];
        console.log(res)
      }
    });

      //  调取微信配置接口
      this.url=location.href;
      var params = new URLSearchParams();
      params.append('url',this.url);
      this.$axios({
        method: 'post',
        url:'gp/cardCancel/getCardCancel',
        data:params
      }).then((res)=> {
        this.wxConfig=res.data;
      console.log(res,1111)
      this.accessToken=res.data.accessToken;
      this.$wx.config({
        beta: true,// 必须这么写，否则wx.invoke调用形式的jsapi会有问题
        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        appId: this.wxConfig.appid, // 必填，企业微信的corpID
        timestamp:this.wxConfig.timestamp, // 必填，生成签名的时间戳
        nonceStr: this.wxConfig.nonceStr, // 必填，生成签名的随机串
        signature: this.wxConfig.signature,// 必填，签名，见附录1
        jsApiList: ['chooseImage','uploadImage','getLocalImgData','downloadImage'] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
      });
    });
    },
    mounted(){},
    methods:{
      handleSelectImg(fileLocate){
        this.$wx.ready(()=>{
          var u = navigator.userAgent;
        var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
        var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端

        var _this=this;
        var syncUpload = function(localIds){
          var localId = localIds.pop();
          _this.$wx.uploadImage({
            localId: localId.toString(), // 需要上传的图片的本地ID，由chooseImage接口获得
            isShowProgressTips:1, // 默认为1，显示进度提示
            success: function (res) {
              //res.serverId 返回图片的服务器端ID
              var serverId = res.serverId; // 返回图片的服务器端ID
              const item={
                serverId:res.serverId,
                tag : '',
                fileLocate:fileLocate,
              }
              _this.mediaAttr.push(item);
              if(localIds.length > 0){
                window.setTimeout(function(){
                  syncUpload(localIds);
                },100);
              }else{
                window.setTimeout(function(){
                  downloadImage(0);
                },100);

              }
            }
          })
        }
        _this.$wx.chooseImage({
          count: 9, // 默认9
          sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
          defaultCameraMode: "batch", //表示进入拍照界面的默认模式，目前有normal与batch两种选择，normal表示普通单拍模式，batch表示连拍模式，不传该参数则为normal模式。（注：用户进入拍照界面仍然可自由切换两种模式）
          success: function (res) {

            var localIds = res.localIds; // 返回选定照片的本地ID列表，

            for(var i=0;i<localIds.length;i++){
              if(isiOS==true){

                _this.$wx.getLocalImgData({
                  localId: localIds[i], // 图片的localID
                  success: function (res) {
                    var localData = res.localData; // localData是图片的base64数据，可以用img标签显示
                    const item={
                      src:localData,
                      tag : '',
                      fileLocate:fileLocate,
                    };
                    _this.files.push(item);
                    console.log(_this.files);

                  },
                  fail: function(res) {
                    console.log(res)
                  }
                });
              }else{
                const item={
                  src:localIds[i],
                  tag : '',
                  fileLocate:fileLocate,
                };
                _this.files.push(item);
              }


            }

            syncUpload(res.localIds)
            // andriod中localId可以作为img标签的src属性显示图片；
            // 而在IOS中需通过上面的接口getLocalImgData获取图片base64数据，从而用于img标签的显示
          }
        });
      })
      },
      handleDelImg(index,item){
        this.files.splice(index, 1);
        this.mediaAttr.splice(index, 1);
      },
      /**获取oss配置**/
      getOss(){
        let OSS = require('ali-oss');
        this.client = new OSS({
          region: "oss-cn-shenzhen",
          secure: true,//https
          endpoint: 'oss-cn-shenzhen.aliyuncs.com',
          accessKeyId: "LTAIPCNdQvX5yOwc",
          accessKeySecret: "7bReGAz8bc9aJdK4IAz5KW5fnNOzrQ ",
          bucket: 'rmcbapp'
        });
      },
      toBuffer(ab) {
        var buf = new Buffer(ab.byteLength);
        var view = new Uint8Array(ab);
        for (var i = 0; i < buf.length; ++i) {
          buf[i] = view[i];
        }
        return buf;
      },

      handleAdd(){
        var myreg=/^[1][3,4,5,6,7,8,9][0-9]{9}$/;

        if(this.post.storeName==''){
          Toast({
            message: '请输入门店名称',
            position: 'middle',
            duration: 1000
          });
          return false;
        }
        if(this.post.address==''){
          Toast({
            message: '请输入门店地址',
            position: 'middle',
            duration: 1000
          });
          return false;
        }
        if(this.post.linkPhone==''){
          Toast({
            message: '请输入登录账号',
            position: 'middle',
            duration: 1000
          });
          return false;
        }

        if(!myreg.test(this.post.linkPhone)){
          Toast({
            message: '请输入有效的手机号码',
            position: 'middle',
            duration: 1000
          });
          return false;
        }
        if(this.post.linkName==''){
          Toast({
            message: '请输入用户名',
            position: 'middle',
            duration: 1000
          });
          return false;
        }

        if(this.mediaAttr.length<=0){
          Toast({
            message: '请上传门头照',
            position: 'middle',
            duration: 800
          });
          return false;
        }
        this.getOss();
        var that=this;
        that.post.otherImgOss='';
        that.post.shopImgOss='';
        that.myUploads=[];
        for(var i=0;i<that.mediaAttr.length;i++){

          const mediaId = that.mediaAttr[i].serverId; // 微信多媒体文件id
          const fileLocate = that.mediaAttr[i].fileLocate; // 微信多媒体文件id
          const tag = that.mediaAttr[i].tag; // 微信多媒体文件id
          console.log(1111111111111)
          if(tag==''){
            Indicator.open({
              text: '提交中...',
              spinnerType: 'snake'
            });
            that.$axios({
              method: 'get',
              url:'wx/cgi-bin/media/get?access_token='+that.accessToken+'&media_id='+mediaId,
              responseType:'arraybuffer',
            }).then((res)=>{
              // arrayBuffer转Buffer
              var buffer = that.toBuffer(res.data);
            var destPath = 'store/'+fileLocate+'/'+mediaId+'.jpg'; // OSS文件路径
            console.log(buffer)
            var postitem={}
            that.client.put(destPath, buffer).then((result) => {
              console.log('图片上传阿里云结果', result);
            var item='https://rmcbapp.oss-cn-shenzhen.aliyuncs.com/'+result.name;
            if(fileLocate=='其他'){
              if(that.post.otherImgOss==''){
                that.post.otherImgOss+=item;
              }else{
                that.post.otherImgOss+=','+item;
              }
            }else if(fileLocate=='实体门店图'){

              if(that.post.shopImgOss==''){
                that.post.shopImgOss+=item;
              }else{
                that.post.shopImgOss+=','+item;
              }
            }
            that.myUploads.push(item);
            if(that.myUploads.length==i){

              if(this.post.shopImgOss==''){
                Indicator.close();
                Toast({
                  message: '请上传门头照',
                  position: 'middle',
                  duration: 800
                });
                return false;
              }
              var params = new URLSearchParams();
              params.append('storeName',this.post.storeName);
              params.append('storeType',this.post.storeType);
              params.append('name',this.post.linkName);
              params.append('mobile',this.post.linkPhone);
              params.append('storeAddress',this.post.address);
              params.append('otherImgOss',this.post.otherImgOss)  ;
              params.append('shopImgOss',this.post.shopImgOss);
              that.$axios({
                method: 'post',
                url:'gp/store/addStore',
                data:params
              }).then((res)=>{

                if(res.data.statusCode==200){
                Indicator.close();
                this.popupCorrect=true;
              }else{
                Indicator.close();
                Toast({
                  message: res.data.message,
                  position: 'middle',
                  duration:1000
                });
              }
            }).catch((error)=> {
                Indicator.close();
              Toast({
                message: error,
                position: 'middle',
                duration:2000
              });
            });
            }

          }).catch((err) => {
              console.log(err)
            Toast({
              message: '图片上传失败',
              position: 'middle',
              duration:1000
            });
          });

          })
          }else{
            console.log('该图片已上传')
          }
        };
      },
    }
  }
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
  .salesman-add-user .button-content{
    padding:24px;
  }
  .salesman-add-user .button-content .mint-button{
    background:#c34853;
    display: block;
    width: 100%;
  }
  .salesman-add-user .mint-field .mint-cell-title{
    width:80px;
  }
  .salesman-add-user .select-operator{
    width: 100%;
    min-height:32px;
    border:none;
    outline:none;
    font-size: 16px;
    color: #666;
  }
  .correct-popup{
    width: 100%;
    height:90%;
    display: flex;
    justify-content:center;
    align-items:center;
    text-align: center;
  }
  .correct-popup .tips-content{
    padding:0 0 60px;
  }
  .correct-popup .iconfont{
    display: block;
    margin:0 0 8px;
    font-size: 64px;
    color:#ef3b3c;
    text-align: center;
  }
  .correct-popup .tips{
    font-size: 18px;
    color: #666;
    letter-spacing:2px;
  }

  .salesman-add-user .img-upload-content{
    width:94%;
    margin: 0;
    padding:0 0 16px;
  }
  .salesman-add-user .img-upload-content .item{
    position: relative;
    width:33.2% !important;
    height:60px;
    padding:0 12px 12px 0;
    margin:16px 0 0;
  }
  .salesman-add-user .img-upload-content img{
    width: 100%;
    height: 60px;
  }
  .salesman-add-user .img-upload-content .icon-shanchu{
    background:rgba(225,225,225,0.5) !important;
    position: absolute;
    top:0;
    right:12px;
    width: 20px;
    height: 20px;
    font-size:15px !important;
    color:#fff;
    text-align: center;
    line-height: 24px;
  }
  .salesman-add-user .add-img{
    display: block;
    height: 60px;
    padding:0;
    color: #ddd;
    line-height: 60px;
    text-align: center;
    border:1px dashed #ddd;
  }
  .salesman-add-user .add-img:before{
    display: block;
    margin:0 auto 4px;
    font-size: 24px;
  }
</style>

